package com.hxzy.controller.common;

import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 功能描述
 *
 * @author tonneyyy
 */
@RestController
@Api(tags = "文件上传API")
@RequestMapping(value = "/api")
public class FileUploadController extends BaseController{

    private final String DIR_NAME="D:\\image_server\\";
    private final String URL_NAME="/image/";

    @ApiOperation(value = "图片上传，只支持png,jpg")
    @PostMapping(value = "/image/upload")
    public R imageUpload(MultipartFile file) throws IOException {

        if(file.isEmpty()){
            return R.build(AckCode.FILE_NOT_EMPTY);
        }

        List<String> arr= Arrays.asList(".jpg",".png",".jpeg");

        String originalFilename=file.getOriginalFilename();
        String extend=originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if(!arr.contains(extend)){
            return R.build(AckCode.UPLOAD_TYPE_ERROR_IMAGE);
        }

        String newFileName= UUID.randomUUID().toString()+extend;
        //上传路径
        File newFile=new File(DIR_NAME,newFileName);

        file.transferTo(newFile);

         //返回给前端
        Map<String,Object> data=new HashMap<>();
        data.put("image",URL_NAME+newFileName);
        data.put("fileName",originalFilename);
        return R.okHasData(data);
    }


}
